<?php

namespace App\Http\Controllers\Admin;

use App\Exceptions\FormException;
use App\Services\UploadService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Banner;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class BeginBannerController extends Controller
{
    /**
     * 编辑展示页面
     * @name edit
     * @param \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @author Mr.Liu
     * @return JsonStr
     * @datetime 2019/5/21 9:43
     */
    public function index(){
        $data = Banner::where('origin',Banner::BeginBanner)->orderBy('sort','desc')->first();
        return view('Admin.beginBanner.edit',['data' => $data]);
    }

    /**
     * 编辑AJAX保存操作
     * @name update
     * @param void
     * @author Mr.Liu
     * @return JsonStr
     * @datetime 2019/5/21 10:11
     */
    public function update(Request $request,$id){
        $payload  = $request->only(['jump_url','goods_id']);
        Validator::make($payload, [
            'goods_id'    => 'required_if:jump_url,false',
        ],[
            'jump_url.required' => '请选择跳转地址',
            'goods_id.required_if' => '请选择商品详情',
        ])->validate();

        DB::beginTransaction();

        try{
            $model = Banner::findOrFail($id);

            if($request->hasFile('photo')) {
                $UploadService = new UploadService($request, 'beginBanner', 'photo', 'oss');
                $uploadresult = $UploadService->upload();

                if ($uploadresult['status'] == UploadService::FailStatus) {
                    throw new \Exception($uploadresult->message ?? '图片上传失败');
                }
                $model->photo = $uploadresult['url'];
            }
            if($payload['jump_url']){
                if($payload['jump_url'] != 'false'){
                    $model->jump_url = $payload['jump_url'];
                }else{
                    $model->jump_url = getAppUrl().'goods/'.$payload['goods_id'];
                }
            }
            $model->save();

        }catch (\Exception $exception){
            DB::rollBack();
            throw new FormException(App::environment('local') ? $exception->getMessage() : '保存失败' );
        }
        DB::commit();
        return $this->getResponse('保存成功');
    }
}
